import time
from datetime import datetime
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_DHT
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

pin=4
sensor = Adafruit_DHT.DHT22
RST = 24
DC = 17
SPI_PORT = 0
SPI_DEVICE = 0

disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

disp.begin()
disp.clear()
disp.display()

width = disp.width
height = disp.height
font = ImageFont.truetype('DejaVuSans.ttf', 12)

def welcom():
    welcom = Image.open('./raspberry_logo_wel.png').resize((128, 64), Image.ANTIALIAS).convert('1')    
    # Display welcom_logo.
    disp.image(welcom)
    disp.display()
    time.sleep(1)


def show_info():
    image = Image.open('./raspberry_logo.png').resize((128, 64), Image.ANTIALIAS).convert('1')
    draw = ImageDraw.Draw(image)
    while (1):
        draw.rectangle((50,0,width,height),outline=0,fill=0)        
	def dht22():
    	    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
            if humidity is not None and temperature is not None:
    	    #print('Temp:{0:0.1f}*C  Humidity:{1:0.1f}%'.format(temperature, humidity))
                dht22_info=['Temp:{0:0.1f}*C '.format(temperature,humidity),'Hum:{1:0.1f}%'.format(temperature,humidity)]
            else:
                #print('Failed to get reading. Try again!')
        	dht22_info=['Temp:ERROR!','Hum:ERROR!']
    	    return dht22_info
	
	# display temp and hum
        draw.text((50,2),str(datetime.now().strftime('%Y-%m-%d')),font=font,fill=1)
        draw.text((50,18),str(datetime.now().strftime('%H:%M:%S')),font=font,fill=1)
        draw.text((50,34), dht22()[1], font=font,fill=1)
        draw.text((50, 50), dht22()[0], font=font, fill=1)
        # Display image.
        disp.image(image)
        disp.display()
        time.sleep(1)

def bye_bye():
    bye = Image.open('./raspberry_logo_bye.png').resize((128, 64), Image.ANTIALIAS).convert('1')
    # Display bye_logo.
    disp.image(bye)
    disp.display()
    time.sleep(2)
    disp.clear()
    disp.display()	

if __name__=='__main__':
    welcom()
    try:
	show_info()
    except:
	bye_bye()
